<template>
  <Dialog :title="title" :model-value="visible" width="800px" :before-close="closeForm">
    <Table
      ref="roleTable"
      :data="roles"
      row-key="Id"
      :columns="columns"
      style="width: 100%"
      :isSelect="true"
      v-model:selectKey="roleId"
    >
      <template #IsAdmin="e">
        <span v-if="e.row.IsAdmin">管理员</span>
      </template>
    </Table>
    <p v-if="roleId.length == 0" style="color: #f56c6c; text-align: center"> 至少选择一个角色! </p>
    <template #footer>
      <el-space style="text-align: center">
        <el-button :disabled="roleId.length == 0" type="primary" @click="save">保存</el-button>
        <el-button @click="closeForm">取消</el-button>
      </el-space>
    </template>
  </Dialog>
</template>

<script>
import { getSelect } from '@/api/role/role'
import * as empRoleApi from '@/api/role/empRole'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
export default {
  components: {
    Dialog,
    Table
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '设定人员角色'
    },
    empId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roles: [],
      roleId: [],
      addVisible: false,
      columns: [
        {
          field: 'RoleName',
          label: '角色名',
          align: 'left',
          minWidth: 150
        },
        {
          field: 'Remark',
          label: '备注',
          align: 'center',
          minWidth: 120
        },
        {
          field: 'IsAdmin',
          label: '是否是管理员',
          align: 'center',
          slotName: 'IsAdmin',
          minWidth: 100
        }
      ]
    }
  },
  computed: {
    comId() {
      return userStore.comId
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.load()
        }
      },
      immediate: true
    }
  },
  methods: {
    async load() {
      this.roles = await getSelect()
      this.loadEmpRole()
    },
    async save() {
      if (this.roleId.length === 0) {
        return
      }
      await empRoleApi.set(this.empId, this.roleId)
      this.$message({
        type: 'success',
        message: '设置成功!'
      })
      this.$emit('update:visible', false)
      this.$emit('close', true)
    },
    selectChange(rows) {
      this.roleId = rows.map((c) => c.Id)
    },
    async loadEmpRole() {
      const ids = await empRoleApi.get(this.empId)
      if (this.roleId == null) {
        this.roleId = []
      } else {
        this.roleId = ids
      }
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    }
  }
}
</script>
